package com.peppa.common.grayconfig.Strategy;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.peppa.common.grayconfig.Strategy.factory.AnnoStrategy;
import com.peppa.common.grayconfig.ThreadAttributes;
import org.springframework.cloud.netflix.ribbon.eureka.EurekaServerIntrospector;

import java.util.List;
import java.util.StringTokenizer;

/**
 * @author ：杜戈
 * @date ：Created in 2019-08-22 16:15
 * @description：使用请求中header的server-ip列表选择服务器
 */
@AnnoStrategy
public class HeaderServerIplistStrategy extends StrategyAbstract{
    private final String header_key = "svips";

    public HeaderServerIplistStrategy() {
        setName(H_SVIP);
        setOrder(SORT_H_SVIP);
    }

    @Override
    public Server getServer(ILoadBalancer balancer){
        String svips = ThreadAttributes.getHeaderValue(header_key);
        if (svips == null || svips.equals("")){
            logger.info("HTTP header svips:---null!!!");
            return null;
        }
        logger.info("HTTP header svips:---{}",svips);
        StringTokenizer stringTokenizer = new StringTokenizer(svips,DELIM_ITEM);
        String serverDiscoverName = null;
        while (stringTokenizer.hasMoreElements()) {
            if (serverDiscoverName == null){
                serverDiscoverName = getDiscoverName(balancer);
                if (serverDiscoverName ==null){
                    return null;
                }
            }
            String svip = stringTokenizer.nextToken();
            int ind = svip.indexOf(DELIM_VALUE);
            if(ind<=0||svip.length()==ind+1)
                continue;
            String servername = svip.substring(0,ind).trim();
            String ip = svip.substring(ind+1).trim();
            if (serverDiscoverName.equals(servername)){
                Server retserver = getIpSameServer(ip,balancer);
                if (retserver!=null){
                    return retserver;
                }
            }
        }
        return null;
    }

    /**
     * 获得服务的eureka的注册名
     * @param balancer
     * @return
     */
    String getDiscoverName(ILoadBalancer balancer){
        EurekaServerIntrospector serverIntrospector = new EurekaServerIntrospector();
        List<Server> servers = balancer.getReachableServers();
        for (Server server : servers) {
            return server.getMetaInfo().getAppName();
        }
        return null;
    }
    @Override
    public String getName(){
        return name;
    }
}
